package com.xbongbong.paas.service.stage.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasStageEntity;
import com.xbongbong.paas.domain.entity.StageProcessEntity;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.model.PaasStageModel;
import com.xbongbong.paas.model.StageProcessModel;
import com.xbongbong.paas.service.stage.AbstractStageHandleImpl;
import com.xbongbong.paas.service.stage.StageHandle;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.script.pojo.dto.StageSettingScriptDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Paas 阶段策略
 * @author 李少杰
 * @version v1.0.0
 * @date 2021/11/22 17:52
 */
@Service("paasStageHandle")
public class PaasStageHandle extends AbstractStageHandleImpl implements StageHandle {

    private static final Logger LOG = LoggerFactory.getLogger(PaasStageHandle.class);
    @Resource
    private PaasStageModel paasStageModel;
    @Resource
    private StageProcessModel stageProcessModel;


    @Override
    public Integer businessType() {
        return XbbRefTypeEnum.PAAS.getCode();
    }

    @Override
    public PaasStageEntity getByKey(Long stageId, String corpid) {
        return paasStageModel.getByKey(stageId, corpid);
    }

    @Override
    public List<PaasStageEntity> findEntitys(Map<String, Object> params) {
        return paasStageModel.findEntitys(params);
    }

    @Override
    public Integer insert(PaasStageEntity entity) throws XbbException {
        entity.setUpdateTime(DateTimeUtil.getInt());
        entity.setAddTime(DateTimeUtil.getInt());
        return paasStageModel.insert(entity);
    }

    @Override
    public Integer update(PaasStageEntity entity) throws XbbException {
        entity.setUpdateTime(DateTimeUtil.getInt());
        return paasStageModel.update(entity);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return paasStageModel.getEntitysCount(param);
    }

    @Override
    public Integer deleteBatch(List<PaasStageEntity> paasStageEntityList, String corpid) {
        return paasStageModel.deleteBatch(paasStageEntityList, corpid);
    }

    @Override
    public void insertBatch(List<PaasStageEntity> list) {
        list.forEach(item -> {
            item.setAddTime(DateTimeUtil.getInt());
            item.setUpdateTime(DateTimeUtil.getInt());
        });
        paasStageModel.insertBatch(list);
    }

    @Override
    public void insertBatch4Script(List<PaasStageEntity> list) {

    }

    @Override
    public void updateBatch(List<PaasStageEntity> list, String corpid) {
        list.forEach(item -> item.setUpdateTime(DateTimeUtil.getInt()));
        paasStageModel.updateBatch(list, corpid);
    }

    @Override
    public void updateBatchDefaultAndLinkOption(List<PaasStageEntity> list, String corpid) {
        list.forEach(item -> item.setUpdateTime(DateTimeUtil.getInt()));
        paasStageModel.updateBatchDefaultAndLinkOption(list, corpid);
    }

    @Override
    public void updateBatch4MirrorRollback(List<PaasStageEntity> list, String corpid) {
        paasStageModel.updateBatch4MirrorRollback(list, corpid);
    }

    @Override
    public void updateBatch4Script(List<PaasStageEntity> list) {

    }

    @Override
    public PaasStageEntity getByCode(String corpid, Long formId, String stageCode) {
        return paasStageModel.getByCode(corpid, formId, stageCode);
    }

    @Override
    public List<ItemPoJo> getStageByStageProgress(Map<String, Object> params, Long formId, String corpid) throws XbbException {
        List<PaasStageEntity> paasStageEntities = paasStageModel.findEntitys(params);
        if (CollectionsUtil.isEmpty(paasStageEntities)){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return updateStageInfoInExplain(paasStageEntities, formId, corpid);
    }

    @Override
    public void updateStageDefaultAndOption(List<FieldAttrEntity> explains, Long formId, String corpid) throws XbbException {
        FieldAttrEntity fieldAttrEntity = null;
        List<PaasStageEntity> updatePaasStageEntities = new ArrayList<>();
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        try {
            for (FieldAttrEntity fieldEntity : explains) {
                if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), fieldEntity.getFieldType())) {
                    fieldAttrEntity = fieldEntity;
                    break;
                }
            }
            if (Objects.isNull(fieldAttrEntity)) {
                return;
            }
            List<ItemPoJo> itemPojos = fieldAttrEntity.getItems();
            if (CollectionsUtil.isEmpty(itemPojos)) {
                return;
            }
            Long stageProcessId;
            if (Objects.equals(fieldAttrEntity.getStageMultiVersion(), 1)) {
                // 开启多版本启用的时候，表单设计页显示的阶段是默认版本的阶段
                stageProcessId = fieldAttrEntity.getDefaultStageProcessId();
                if (Objects.isNull(stageProcessId)) {
                    return;
                }
            } else {
                // 单版本启用的时候，表单设计页显示的阶段是当前启用版本的阶段
                StageProcessEntity stageProcessEntity = stageProcessModel.getEnableStageProcess(corpid, formId);
                if (Objects.isNull(stageProcessEntity)) {
                    return;
                }
                stageProcessId = stageProcessEntity.getId();
            }
            params.put(ParameterConstant.CORPID, corpid);
            params.put(ParameterConstant.FORMID, formId);
            params.put(ParameterConstant.DEL, BasicConstant.ZERO);
            params.put(ParameterConstant.ENABLE, BasicConstant.ONE);
            params.put(ParameterConstant.STAGE_PROCESS_ID, stageProcessId);
            params.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT + " " + SortOrder.DESC);
            List<PaasStageEntity> paasStageEntities = paasStageModel.findEntitys(params);
            Map<String, PaasStageEntity> paasStageEntityMap = paasStageEntities.stream().collect(Collectors.toMap(PaasStageEntity::getCode, Function.identity()));
            for (ItemPoJo item : itemPojos) {
                PaasStageEntity paasStageEntity = paasStageEntityMap.get(String.valueOf(item.getValue()));
                if (Objects.equals(item.getChecked(),true)) {
                    paasStageEntity.setIsDefault(BasicConstant.ONE);
                } else {
                    paasStageEntity.setIsDefault(BasicConstant.ZERO);
                }
                if (Objects.nonNull(item.getFieldMap())) {
                    paasStageEntity.setLinkOption(JSONArray.parseArray(JSON.toJSONString(item.getFieldMap())));
                } else {
                    paasStageEntity.setLinkOption(null);
                }
                paasStageEntity.setUpdateTime(DateTimeUtil.getInt());
                updatePaasStageEntities.add(paasStageEntity);
            }
            paasStageModel.updateBatch(updatePaasStageEntities, corpid);
        } catch (Exception e) {
            LOG.error("PaasStageHandle.updateStageDefaultAndOption 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

}
